# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/4/28 15:17
"""
import random
import time
from dataclasses import dataclass
from typing import Optional, List

import pyautogui
import pyperclip
from DrissionPage import WebPage
from DrissionPage.action_chains import ActionChains
from DrissionPage.commons.keys import Keys

from autoTask.taobao.sycm.goods.findMarketRank import CacheAction
from autoTask.taobao.sycm.utils import WaitUtil
from common.logger.log import log_
from common.utils import web_page_util, ExcelUtil, FileUtil
from common.utils.DateUtil import seconds_until_end_of_day
from common.utils.web_page_util import MockTap, Tap


@dataclass
class GetDataAction:
    """
    获取市场排行商品操作

    Attributes:
        category (str): 产品类别。
        date_cycle (str): 数据周期，例如 '7天', '30天' ,'日'
        p (WebPage): 网页对象
    """
    category: str
    date_cycle: str
    p: Optional[WebPage] = None

    def __call__(self, p: WebPage) -> List:
        self.p = p
        # 跳转至任务首页
        self.goto_index()
        # 设置页面数据显示条件
        self.set_data_condition()
        # 尝试从缓存中获取
        result = CacheAction.get_cache(category=self.category, data_cycle=self.date_cycle)
        if result:
            return result
        # 打开小旺神一键复制
        text = self.copy_data_action()
        result = ExcelUtil.pd_paste_2_csv(text).values.tolist()
        # 设置到缓存
        CacheAction.set_cache(category=self.category, data_cycle=self.date_cycle, value=result,
                              export=seconds_until_end_of_day(1))
        return result

    def call_v2(self, p: WebPage) -> str:
        """
        :param p: 网页对象
        :return:         返回下载的表格路径
        """
        self.p = p
        # 跳转至任务首页
        self.goto_index()
        # 设置页面数据显示条件
        self.set_data_condition()
        # 尝试从缓存中获取
        result = CacheAction.get_excel_cache(category=self.category, data_cycle=self.date_cycle)
        if result:
            return result
        # 打开小旺神导出表格
        result = self.dw_tb_action()
        # 设置到缓存
        CacheAction.set_excel_cache(excel_path=result, category=self.category, data_cycle=self.date_cycle,
                                    export=seconds_until_end_of_day(1))
        return result

    def goto_index(self):
        """
        跳转到任务首页
        :return:
        """
        if not self.p.url.startswith("https://sycm.taobao.com/mc/mq/market_rank?activeKey=item"):
            # 如果在登录成功页 则跳转到生意参谋页
            if self.p.url.startswith("https://myseller.taobao.com/home.htm/QnworkbenchHome/") or self.p.url.startswith(
                    "https://www.taobao.com/"):
                self.p.get("https://sycm.taobao.com/portal/home.htm")
                self.p.wait.load_start(30)
            MockTap(self.p("x://span[.='市场']"), "跳转到 [市场] 标签页失败", before_delay=(1, 3))()
            self.p.wait.load_start(30)
            MockTap(self.p("x://span[.='市场排行']"), "跳转到 [市场排行] 标签页失败", before_delay=(1, 3))()
            self.p.wait.load_start(30)
            MockTap(self.p("x://div[@class='ebase-FaCommonFilter-module__bottom']")("tx:商品"),
                    "跳转到 [商品] 标签页失败",
                    before_delay=(1, 3), scope_random=False)()
            self.p.wait.load_start(30)

    def set_data_condition(self):
        """
        设置表格数据分页条件
        :return:
        """
        # 设置当前商品品类
        if not self.p(f"@@class=common-picker-header@@title:{self.category}"):
            log_.info(f"设置品类 :{self.category}")
            # 点击下拉框
            MockTap(self.p(".common-picker-header"), "打开设置商品类型下拉窗失败", after_delay=3)()
            # 输入关键词搜索
            self.p("@@class=ant-input@@placeholder:请输入关键字").input(self.category)
            time.sleep(3)
            # 点击对应关键词
            MockTap(self.p(f"@@class^oui-typeahead-dropdown-item@@text():{self.category}"),
                    "点击搜索结果中的关键词失败")()
        # 设置当前数据周期
        e = None
        if self.date_cycle == '30天':
            e = self.p("text=30天", timeout=5)
        elif self.date_cycle == '7天':
            e = self.p("text=7天", timeout=5)
        if not e and self.date_cycle != '7天':
            # 修正存入缓存值的key 防止变成了 30天
            self.date_cycle = '7天'
            e = self.p("text=7天", timeout=5)
        # 已经被选中了不再点击
        if e.parent().attr("class") != "ant-btn oui-canary-btn ant-btn-primary ant-btn-sm":
            log_.info("设置数据周期")
            MockTap(e, "设置数据周期失败")()
            # 等待加载完毕
            WaitUtil.wait_tb_complete(self.p)

    def copy_data_action(self) -> str:
        """
        获取(一键复制)数据操作
        :return: 一键复制得到数据
        """
        tb_list = ["高流量", "高意向", "高交易"]
        random.shuffle(tb_list)
        for item in tb_list:
            MockTap(self.p(f"@@class^oui-tab-switch-item@@text():{item}"),
                    f"点击跳转到{item}界面失败")()
            WaitUtil.wait_tb_complete(self.p)
        self.open_xws_cvs_view()
        # 滑动到底部 加载数据
        self.p(".el-pagination__total", timeout=30).scroll.to_see()
        # 等待加载完毕
        web_page_util.wait_ele_disappear(self.p, ".el-loading-mask", 10)
        time.sleep(3)
        MockTap(self.p("x://div[@class='header-right']//span[contains(.,'一键复制')]"),
                "点击小旺神复制表格时失败", after_delay=(3, 5))()
        pyautogui.press('esc')
        return pyperclip.paste()

    def dw_tb_action(self) -> str:
        """
        下载表格操作
        :return: 返回表格路径
        """
        tb_list = ["高流量", "高意向", "高交易"]
        random.shuffle(tb_list)
        for item in tb_list:
            MockTap(self.p(f"@@class^oui-tab-switch-item@@text():{item}"),
                    f"点击跳转到{item}界面失败")()
            WaitUtil.wait_tb_complete(self.p)
        self.open_xws_cvs_view()
        # 滑动到底部 加载数据
        self.p(".el-pagination__total", timeout=30).scroll.to_see()
        # 等待加载完毕
        web_page_util.wait_ele_disappear(self.p, ".el-loading-mask", 10)
        time.sleep(3)
        dw_path = FileUtil.get_project_root() + r"/DownloadData/sycm_table/goods/excel"
        FileUtil.clear_folder(dw_path, ".keep")
        self.p.download_set.save_path(dw_path)
        self.p("tx:导出xlsx表格（带图片）").click(by_js=True)
        ActionChains(self.p).key_down(Keys.ESCAPE)
        file_paths = FileUtil.find_file(dw_path, "*小旺神*", timeout=60)
        if len(file_paths) == 0:
            raise RuntimeError("下载数据表格时失败")
        return file_paths[0]

    def open_xws_cvs_view(self):
        e = None
        for i in range(0, 5):
            e = self.p("@@class:xws-cur-button@@text():合并转化")
            if e:
                break
            self.p.refresh()
            self.p.wait.load_complete()
        Tap(e, "打开小旺神合并转化失败", by_js=True)()
